package com.ruicar.afs.cloud.apply.admin.auth.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.ruicar.afs.cloud.admin.service.SysUserService;
import com.ruicar.afs.cloud.apply.admin.auth.util.ChannelDic;
import com.ruicar.afs.cloud.apply.admin.auth.util.ChineseCharacterUtil;
import com.ruicar.afs.cloud.apply.admin.auth.util.DataAccessUtil;
import com.ruicar.afs.cloud.apply.admin.manage.condition.StartOrStopDTO;
import com.ruicar.afs.cloud.apply.admin.manage.entity.*;
import com.ruicar.afs.cloud.apply.admin.manage.mapper.ApplyUserMapper;
import com.ruicar.afs.cloud.apply.admin.manage.service.*;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.apply.dto.*;
import com.ruicar.afs.cloud.common.modules.apply.enums.*;
import com.ruicar.afs.cloud.parameter.commom.enums.CarType;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author: Lee
 * @date: 2020/5/11 19:39
 * @description: 外部接口用controller
 * 用户新增，如果选择的部门授权区域只有新车的授权区域，则只能给用户绑定新车角色，如果选择的部门授权区域有二手车，则新增的用户可以选择二手车角色
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/applyAuth")
public class ExternalInterfaceController {
    //默认用户名称
    private final String defaultUserRealName = "管理员";

    private final ApplyDepartmentService applyDepartmentService;
    private final ApplyChannelAuthRegionService applyChannelAuthRegionService;
    private final ApplyUserService applyUserService;
    private final ApplyDeptAuthRegionService applyDeptAuthRegionService;
    private final ApplyRoleService applyRoleService;
    private final ApplyUserRoleService applyUserRoleService;
    private final ApplyPermissionService applyPermissionService;
    private final ApplyRolePermissionService applyRolePermissionService;
    private final ApplyChannelBasicInfoService applyChannelBasicInfoService;
    private final ApplyChannelWitnessInfoService applyChannelWitnessInfoService;

    private final ApplySysUserStopRecordService applySysUserStopRecordService;
    private final SysUserPowerService sysUserPowerService;
    private final ApplyUserMapper applyUserMapper;

    private final ApplyUserTempService applyUserTempService;
    private final ApplyUserRoleTempService applyUserRoleTempService;

    @Transactional
    @PostMapping("/createUser")
    @ApiOperation(value = "初始化创建用户")
    public IResponse<Boolean> initCreateUser(@Validated @RequestBody ChannelBasicInfoDTO channelBasicInfo) {
        //step1: 保存渠道基本信息
        SysChannelBasicInfo one = applyChannelBasicInfoService.getOne(Wrappers.<SysChannelBasicInfo>query().lambda()
                .eq(SysChannelBasicInfo::getChannelId, channelBasicInfo.getChannelId()));
        if (one != null) {
            //   BeanUtils.copyProperties  用于属性拷贝: 把  channelBasicInfo赋值给  one
            BeanUtils.copyProperties(channelBasicInfo, one);
            one.setNewCarUserHierarchy(channelBasicInfo.getNewCarUserHierarchy());
            one.setOldCarUserHierarchy(channelBasicInfo.getOldCarUserHierarchy());
            one.setChannelBelong(channelBasicInfo.getChannelBelong());
            one.setChoiceCardealerSwitch(channelBasicInfo.getChoiceCardealerSwitch());
            //add by mingzhi.li  2020-10-09 11:27:39 二手车进件是否关联车商
            one.setChoiceCardealerSwitchOld(channelBasicInfo.getChoiceCardealerSwitchOld());
            //add by mingzhi.li  2020-10-09 11:27:39 二手车进件是否关联车商
            applyChannelBasicInfoService.updateById(one);
        } else {
            SysChannelBasicInfo basicInfo = new SysChannelBasicInfo();
            BeanUtils.copyProperties(channelBasicInfo, basicInfo);
            applyChannelBasicInfoService.save(basicInfo);
        }

        //step2: 创建顶级部门
        SysDepartment dept = new SysDepartment();
        dept.setChannelId(channelBasicInfo.getChannelId());
        dept.setIsParent(false);
        dept.setTitle(channelBasicInfo.getChannelFullName());
        dept.setParentId(Long.valueOf(AfsEnumUtil.key(CreatUserEnum.DEFAULT_DEPT_PARENT)));
        dept.setStatus(LockFlagEnum.YES.getValue());
        dept.setSortOrder(BigDecimal.ZERO);
        List<SysDepartment> applyDepartments = applyDepartmentService.list(Wrappers.<SysDepartment>query().lambda().
                eq(SysDepartment::getChannelId, channelBasicInfo.getChannelId()));
        Long deptId;
        if (ObjectUtils.isEmpty(applyDepartments)) {
            applyDepartmentService.save(dept);
            deptId = dept.getId();
        } else {
            deptId = applyDepartments.get(0).getId();
        }

        /**
         * step3: 为部门增加授权区域
         * 部门授权区域初始化会保存两条数据，第一条是deptid=0的，第二条是真实的deptId。
         * 这样做是为了，后面增加部门时，方便获取上级部门的授权区域
         */
        //  ice 理解这个是为了清空之前的所有的关于这个区域的关联的省市区
        applyDeptAuthRegionService.remove(Wrappers.<SysDeptAuthRegion>query().lambda().eq(SysDeptAuthRegion::getChannelId, channelBasicInfo.getChannelId()).eq(SysDeptAuthRegion::getDeptId,AfsEnumUtil.key(CreatUserEnum.DEFAULT_DEPT_PARENT)));
        List<SysChannelAuthRegion> newCarChannelAuthRegion = applyChannelAuthRegionService.list(Wrappers.<SysChannelAuthRegion>query().lambda().
                eq(SysChannelAuthRegion::getChannelId, channelBasicInfo.getChannelId()).eq(SysChannelAuthRegion::getBusinessType, CarTypeEnum.newCar));
        List<SysChannelAuthRegion> oldCarChannelAuthRegion = applyChannelAuthRegionService.list(Wrappers.<SysChannelAuthRegion>query().lambda().
                eq(SysChannelAuthRegion::getChannelId, channelBasicInfo.getChannelId()).eq(SysChannelAuthRegion::getBusinessType, CarTypeEnum.oldCar));

        List<SysChannelAuthRegion> channelAuthRegion = new ArrayList<>();
        channelAuthRegion.addAll(newCarChannelAuthRegion);
        channelAuthRegion.addAll(oldCarChannelAuthRegion);
        // 这个是为了把渠道传递过来的是省市区 SysChannelAuthRegion 表  转成  SysDeptAuthRegion 表里的数据
        List<SysDeptAuthRegion> sysDeptAuthRegions = JSONUtil.parseArray(channelAuthRegion).toList(SysDeptAuthRegion.class);
        for (SysDeptAuthRegion d : sysDeptAuthRegions) {
            d.setDeptId(Long.valueOf(AfsEnumUtil.key(CreatUserEnum.DEFAULT_DEPT_PARENT)));
            d.setIsChecked(true);
        }
        //第一次保存父级的授权区域  暨 deptId=0
        // applyDeptAuthRegionService.saveBatch(sysDeptAuthRegions);
        int deptSize = sysDeptAuthRegions.size();
        if (deptSize <= 1000) {
            applyDeptAuthRegionService.saveBatch(sysDeptAuthRegions);
        } else {
            for (int i = 0; i < deptSize / 1000; i++) {
                if (deptSize / 1000 - i > 1) {
                    applyDeptAuthRegionService.saveBatch(sysDeptAuthRegions.subList(1000 * i, 1000 * i + 999));
                } else {
                    applyDeptAuthRegionService.saveBatch(sysDeptAuthRegions.subList(1000 * i, deptSize - 1));
                }

            }
        }
        // 先删除一次原来管理员带着的数据
        applyDeptAuthRegionService.remove(Wrappers.<SysDeptAuthRegion>query().lambda().eq(SysDeptAuthRegion::getChannelId, channelBasicInfo.getChannelId()).eq(SysDeptAuthRegion::getDeptId,deptId));
        List<SysDeptAuthRegion> list = JSONUtil.parseArray(channelAuthRegion).toList(SysDeptAuthRegion.class);
        BeanUtils.copyProperties(sysDeptAuthRegions, list);
        for (SysDeptAuthRegion d : list) {
            d.setDeptId(deptId);
            d.setIsChecked(true);
        }
        //保存自身部门结构
        // applyDeptAuthRegionService.saveBatch(list);

        int size = list.size();
        if (size <= 1000) {
            applyDeptAuthRegionService.saveBatch(list);
        } else {
            for (int i = 0; i < size / 1000; i++) {
                if (size / 1000 - i > 1) {
                    applyDeptAuthRegionService.saveBatch(list.subList(1000 * i, 1000 * i + 999));
                } else {
                    applyDeptAuthRegionService.saveBatch(list.subList(1000 * i, size - 1));
                }

            }
        }


        //step4: 初始化角色，如果没有admin角色，创建一个admin角色
//        SysRole role = applyRoleService.getOne(Wrappers.<SysRole>query().lambda()
//                .eq(SysRole::getRoleCode, AfsEnumUtil.key(CreatUserEnum.DEFAULT_ROLE_CODE)));
//
//        Long roleId ;
//        if(ObjectUtils.isEmpty(role)){
//            SysRole applyRole = new SysRole();
//            applyRole.setRoleName("默认管理员角色");
//            applyRole.setDsType(DataTypeEnum.all);
//            applyRole.setRoleCode(AfsEnumUtil.key(CreatUserEnum.DEFAULT_ROLE_CODE));
//            //管理员角色赋予新车、二手车角色类型
//            applyRole.setRoleType(CarTypeEnum.newCar+","+ CarTypeEnum.oldCar);
//            applyRoleService.save(applyRole);
//            roleId = applyRole.getId();
//            List<SysPermission> permissions = applyPermissionService.list(Wrappers.<SysPermission>query().lambda().
//                    in(SysPermission::getTenantHideFlag, CommonConstants.STATUS_NORMAL));
//            List<SysRolePermission> rolePermissions = Lists.newArrayList();
//            //默认赋予admin角色全部菜单权限
//            permissions.forEach(en ->{
//                SysRolePermission rolePermission = new SysRolePermission();
//                rolePermission.setPermissionId(String.valueOf(en.getId()));
//                rolePermission.setRoleId(String.valueOf(roleId));
//                rolePermissions.add(rolePermission);
//            });
//            applyRolePermissionService.saveBatch(rolePermissions);
//        }else{
//            roleId = role.getId();
//        }

        /**
         * step5: 创建用户
         * 渠道管理员账号的规则，还是取名称前6位，不足6位用0补足，如果重复在名称后追加01-99的数字
         */
        SysUser user = new SysUser();

        // 声明一个接受最新的用户信息
        SysUser newUser = new SysUser();
        String channelName = channelBasicInfo.getChannelFullName();
        if (channelName.length() > 6) {
            channelName = channelName.substring(0, 6);
        }
        String userName = StringUtils.rightPad(ChineseCharacterUtil.getLowerCase(channelName, false), 6, "0");
        List<String> userNames = applyUserService.findUserName(userName);
        if (userNames != null && userNames.size() > 0) {
            for (int i = 1; i <= 99; i++) {
                String p = StringUtils.leftPad(String.valueOf(i), 2, "0");
                String newUserName = userName + p;
                if (!userNames.contains(newUserName)) {
                    userName = newUserName;
                    break;
                }
            }
        }
        user.setLastPassChangeTime(0L);
        user.setLastLoginFailTime(0L);
        user.setPassErrorCount(0);
        user.setUsername(userName);
        user.setPhone(channelBasicInfo.getPhone());
        user.setUserEmail(channelBasicInfo.getEmail());
        user.setChannelId(channelBasicInfo.getChannelId());
        user.setPassword(SysUserService.ENCODER.encode(AfsEnumUtil.key(CreatUserEnum.DEFAULT_PWD)));
        user.setUserRealName(channelBasicInfo.getChannelAdmin());
        user.setLockFlag(CommonConstants.STATUS_NORMAL);
        user.setDeptId(deptId);
        user.setIdentityNumber(channelBasicInfo.getIdentityNumber());
        user.setCreateTime(new Date(System.currentTimeMillis()));
        List<SysUser> u = applyUserService.list(Wrappers.<SysUser>query().lambda()
                .eq(SysUser::getIdentityNumber, channelBasicInfo.getIdentityNumber())
                .eq(SysUser::getChannelId, channelBasicInfo.getChannelId()));
        //step6: 为用户绑定角色
        Long newRoleId = null;
        Long oldRoleId = null;
        if (u.size()<=0) {
            applyUserService.save(user);
            newUser =user;

            // 把这条数据也存到临时表里
            SysUserTemp temp =new SysUserTemp();
            temp.setId(user.getUserId());
            temp.setUsername(user.getUsername());
            temp.setUserRealName(user.getUserRealName());
            temp.setUserEmail(user.getUserEmail());
            temp.setPassword(user.getPassword());
            temp.setPhone(user.getPhone());
            temp.setDeptId(user.getDeptId());
            temp.setChannelId(user.getChannelId());
            temp.setIdentityNumber(user.getIdentityNumber());
            temp.setNewStatus(StatusEnum.PASS.getValue());
            temp.setOldStatus(StatusEnum.PASS.getValue());
            temp.setLockFlag(StatusEnum.NO.getValue());
            temp.setCreateTime(new Date(System.currentTimeMillis()));
            applyUserTempService.save(temp);

            if (newCarChannelAuthRegion.size() > 0 && oldCarChannelAuthRegion.size() > 0) {
                // 说明这个角色新车二手车都有
                if (ChannelDic.CHANNEL_BELONG_SP.equals(channelBasicInfo.getChannelBelong()) || ChannelDic.CHANNEL_BELONG_TOTAL.equals(channelBasicInfo.getChannelBelong())) {
                    // 进入这里说明是SP 或者总对总
                    SysRole newRole = applyRoleService.getOne(Wrappers.<SysRole>query().lambda()
                            .eq(SysRole::getRoleCode, AfsEnumUtil.key(CreatUserEnum.ROLE_NEW_CHANNEL_ADMIN)));
                    newRoleId = newRole.getId();
                    SysRole oldRole = applyRoleService.getOne(Wrappers.<SysRole>query().lambda()
                            .eq(SysRole::getRoleCode, AfsEnumUtil.key(CreatUserEnum.ROLE_OLD_CHANNEL_ADMIN)));
                    oldRoleId = oldRole.getId();
                } else if (ChannelDic.CHANNEL_BELONG_DIRECTLY.equals(channelBasicInfo.getChannelBelong())) {
                    // 进来说明  直营
                    SysRole newRole = applyRoleService.getOne(Wrappers.<SysRole>query().lambda()
                            .eq(SysRole::getRoleCode, AfsEnumUtil.key(CreatUserEnum.ROLE_NEW_DIRECT_ADMIN)));

                    SysRole oldRole = applyRoleService.getOne(Wrappers.<SysRole>query().lambda()
                            .eq(SysRole::getRoleCode, AfsEnumUtil.key(CreatUserEnum.ROLE_OLD_DIRECT_ADMIN)));
                    newRoleId = newRole.getId();
                    oldRoleId = oldRole.getId();

                }

            } else if (newCarChannelAuthRegion.size() > 0) {
                // 进去新车
                if (ChannelDic.CHANNEL_BELONG_SP.equals(channelBasicInfo.getChannelBelong()) || ChannelDic.CHANNEL_BELONG_TOTAL.equals(channelBasicInfo.getChannelBelong())) {
                    // 进入这里说明是SP 或者总对总
                    SysRole newRole = applyRoleService.getOne(Wrappers.<SysRole>query().lambda()
                            .eq(SysRole::getRoleCode, AfsEnumUtil.key(CreatUserEnum.ROLE_NEW_CHANNEL_ADMIN)));

                    newRoleId = newRole.getId();
                } else if (ChannelDic.CHANNEL_BELONG_DIRECTLY.equals(channelBasicInfo.getChannelBelong())) {
                    // 进来说明  直营
                    SysRole newRole = applyRoleService.getOne(Wrappers.<SysRole>query().lambda()
                            .eq(SysRole::getRoleCode, AfsEnumUtil.key(CreatUserEnum.ROLE_NEW_DIRECT_ADMIN)));
                    newRoleId = newRole.getId();
                }

            } else if (oldCarChannelAuthRegion.size() > 0) {
                // 进来二手车
                if (ChannelDic.CHANNEL_BELONG_SP.equals(channelBasicInfo.getChannelBelong()) || ChannelDic.CHANNEL_BELONG_TOTAL.equals(channelBasicInfo.getChannelBelong())) {
                    // 进入这里说明是SP 或者总对总
                    SysRole oldRole = applyRoleService.getOne(Wrappers.<SysRole>query().lambda()
                            .eq(SysRole::getRoleCode, AfsEnumUtil.key(CreatUserEnum.ROLE_OLD_CHANNEL_ADMIN)));
                    oldRoleId = oldRole.getId();
                } else if (ChannelDic.CHANNEL_BELONG_DIRECTLY.equals(channelBasicInfo.getChannelBelong())) {
                    // 进来说明  直营
                    SysRole oldRole = applyRoleService.getOne(Wrappers.<SysRole>query().lambda()
                            .eq(SysRole::getRoleCode, AfsEnumUtil.key(CreatUserEnum.ROLE_OLD_DIRECT_ADMIN)));
                    oldRoleId = oldRole.getId();
                }
            }


            //step6: 为用户绑定角色
            if (newCarChannelAuthRegion != null && newCarChannelAuthRegion.size() > 0) {
                SysUserRole userNewRole = new SysUserRole();
                userNewRole.setUserId(user.getUserId());
                userNewRole.setRoleId(newRoleId);
                userNewRole.setBusinessType(CarTypeEnum.newCar);
                applyUserRoleService.save(userNewRole);
                // 下面是为了给临时表赋值
                SysUserRoleTemp roleTemp =new SysUserRoleTemp();
                roleTemp.setUserId(user.getUserId());
                roleTemp.setRoleId(newRoleId);
                roleTemp.setBusinessType(CarTypeEnum.newCar);
                applyUserRoleTempService.save(roleTemp);


            }
            if (oldCarChannelAuthRegion != null && oldCarChannelAuthRegion.size() > 0) {
                SysUserRole userOldRole = new SysUserRole();
                userOldRole.setUserId(user.getUserId());
                userOldRole.setRoleId(oldRoleId);
                userOldRole.setBusinessType(CarTypeEnum.oldCar);
                applyUserRoleService.save(userOldRole);
                // 下面是为了给临时表赋值
                SysUserRoleTemp roleTemp =new SysUserRoleTemp();
                roleTemp.setUserId(user.getUserId());
                roleTemp.setRoleId(oldRoleId);
                roleTemp.setBusinessType(CarTypeEnum.oldCar);
                applyUserRoleTempService.save(roleTemp);
            }




        } else {
            // 去找到属于总账户的
            // 先声明一个总账号角色的id
            SysUser sy =new SysUser();
            if(u.size()==1){
                sy=u.get(0);
            }else {
                // 先查询出来所有的总账号角色信息
                List<SysRole> ro = applyRoleService.list(Wrappers.<SysRole>query().lambda()
                        .in(SysRole::getRoleCode, AfsEnumUtil.key(CreatUserEnum.ROLE_NEW_CHANNEL_ADMIN),AfsEnumUtil.key(CreatUserEnum.ROLE_OLD_CHANNEL_ADMIN), AfsEnumUtil.key(CreatUserEnum.ROLE_NEW_DIRECT_ADMIN),AfsEnumUtil.key(CreatUserEnum.ROLE_OLD_DIRECT_ADMIN)));
                // 放角色id 的集合
                List<Long> roIds=new ArrayList<>();
                if(ro.size()>0){
                    for (SysRole ros : ro) {
                        roIds.add(ros.getId());
                    }
                }else {
                    throw new AfsBaseException("获取合作商角色有误！");
                }
                for (int i=0;i<u.size();i++){
                    // 去查询用户是不是总账
                    List<SysUserRole> sysUserRoles =applyUserRoleService.list(Wrappers.<SysUserRole>query().lambda().in(SysUserRole::getUserId,u.get(i).getUserId()).in(SysUserRole::getRoleId,roIds));
                    if(sysUserRoles.size()>0){
                        sy=u.get(i);
                        break;
                    }
                }
                if(sy==null){
                    throw new AfsBaseException("获取合作商信息有误！");
                }
            }
            Long id=null;
            // 重新查询一次数据
            SysUser us =applyUserService.getById(sy);
            //  更新用户数据
            us.setUserEmail(channelBasicInfo.getEmail());
            us.setPhone(channelBasicInfo.getPhone());
            us.setIdentityNumber(channelBasicInfo.getIdentityNumber());
            us.setUserRealName(channelBasicInfo.getChannelAdmin());
            us.setLockFlag(StatusEnum.NO.getValue());
            applyUserService.updateById(us);
            newUser=us;
            // 更新临时表的管理员数据
            SysUserTemp usTemp=applyUserTempService.getOne(Wrappers.<SysUserTemp>query().lambda().eq(SysUserTemp::getId,us.getUserId()));
            usTemp.setUserEmail(channelBasicInfo.getEmail());
            usTemp.setPhone(channelBasicInfo.getPhone());
            usTemp.setIdentityNumber(channelBasicInfo.getIdentityNumber());
            usTemp.setUserRealName(channelBasicInfo.getChannelAdmin());
            applyUserTempService.update(usTemp,Wrappers.<SysUserTemp>query().lambda().eq(SysUserTemp::getId,us.getUserId()));
            //  先清除正式表的所有数据
            applyUserRoleService.remove(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getUserId, sy.getUserId()));
            // 再清除临时表的所有数据
            applyUserRoleTempService.remove(Wrappers.<SysUserRoleTemp>query().lambda().eq(SysUserRoleTemp::getUserId,sy.getUserId()));

            //step6: 为用户绑定角色
            if (newCarChannelAuthRegion.size() > 0 && oldCarChannelAuthRegion.size() > 0) {
                // 说明这个角色新车二手车都有
                if (ChannelDic.CHANNEL_BELONG_SP.equals(channelBasicInfo.getChannelBelong()) || ChannelDic.CHANNEL_BELONG_TOTAL.equals(channelBasicInfo.getChannelBelong())) {
                    // 进入这里说明是SP 或者总对总
                    SysRole newRole = applyRoleService.getOne(Wrappers.<SysRole>query().lambda()
                            .eq(SysRole::getRoleCode, AfsEnumUtil.key(CreatUserEnum.ROLE_NEW_CHANNEL_ADMIN)));

                    SysRole oldRole = applyRoleService.getOne(Wrappers.<SysRole>query().lambda()
                            .eq(SysRole::getRoleCode, AfsEnumUtil.key(CreatUserEnum.ROLE_OLD_CHANNEL_ADMIN)));
                    newRoleId = newRole.getId();
                    oldRoleId = oldRole.getId();

                } else if (ChannelDic.CHANNEL_BELONG_DIRECTLY.equals(channelBasicInfo.getChannelBelong())) {
                    // 进来说明  直营
                    SysRole newRole = applyRoleService.getOne(Wrappers.<SysRole>query().lambda()
                            .eq(SysRole::getRoleCode, AfsEnumUtil.key(CreatUserEnum.ROLE_NEW_DIRECT_ADMIN)));

                    SysRole oldRole = applyRoleService.getOne(Wrappers.<SysRole>query().lambda()
                            .eq(SysRole::getRoleCode, AfsEnumUtil.key(CreatUserEnum.ROLE_OLD_DIRECT_ADMIN)));
                    newRoleId = newRole.getId();
                    oldRoleId = oldRole.getId();
                }

            } else if (newCarChannelAuthRegion.size() > 0) {
                // 进去新车
                if (ChannelDic.CHANNEL_BELONG_SP.equals(channelBasicInfo.getChannelBelong()) || ChannelDic.CHANNEL_BELONG_TOTAL.equals(channelBasicInfo.getChannelBelong())) {
                    // 进入这里说明是SP 或者总对总
                    SysRole newRole = applyRoleService.getOne(Wrappers.<SysRole>query().lambda()
                            .eq(SysRole::getRoleCode, AfsEnumUtil.key(CreatUserEnum.ROLE_NEW_CHANNEL_ADMIN)));
                    newRoleId = newRole.getId();


                } else if (ChannelDic.CHANNEL_BELONG_DIRECTLY.equals(channelBasicInfo.getChannelBelong())) {
                    // 进来说明  直营
                    SysRole newRole = applyRoleService.getOne(Wrappers.<SysRole>query().lambda()
                            .eq(SysRole::getRoleCode, AfsEnumUtil.key(CreatUserEnum.ROLE_NEW_DIRECT_ADMIN)));
                    newRoleId = newRole.getId();


                }

            } else if (oldCarChannelAuthRegion.size() > 0) {
                // 进来二手车
                if (ChannelDic.CHANNEL_BELONG_SP.equals(channelBasicInfo.getChannelBelong()) || ChannelDic.CHANNEL_BELONG_TOTAL.equals(channelBasicInfo.getChannelBelong())) {
                    // 进入这里说明是SP 或者总对总
                    SysRole oldRole = applyRoleService.getOne(Wrappers.<SysRole>query().lambda()
                            .eq(SysRole::getRoleCode, AfsEnumUtil.key(CreatUserEnum.ROLE_OLD_CHANNEL_ADMIN)));

                    oldRoleId = oldRole.getId();

                } else if (ChannelDic.CHANNEL_BELONG_DIRECTLY.equals(channelBasicInfo.getChannelBelong())) {
                    // 进来说明  直营
                    SysRole oldRole = applyRoleService.getOne(Wrappers.<SysRole>query().lambda()
                            .eq(SysRole::getRoleCode, AfsEnumUtil.key(CreatUserEnum.ROLE_OLD_DIRECT_ADMIN)));

                    oldRoleId = oldRole.getId();
                }
            }

            //step6: 为用户绑定角色
            if (newCarChannelAuthRegion != null && newCarChannelAuthRegion.size() > 0) {
                SysUserRole userNewRole = new SysUserRole();
                userNewRole.setUserId(sy.getUserId());
                userNewRole.setRoleId(newRoleId);
                userNewRole.setBusinessType(CarTypeEnum.newCar);
                applyUserRoleService.save(userNewRole);

                // 给临时表绑定角色
                SysUserRoleTemp roleTemp =new SysUserRoleTemp();
                roleTemp.setUserId(sy.getUserId());
                roleTemp.setRoleId(newRoleId);
                roleTemp.setBusinessType(CarTypeEnum.newCar);
                applyUserRoleTempService.save(roleTemp);
            }
            if (oldCarChannelAuthRegion != null && oldCarChannelAuthRegion.size() > 0) {
                SysUserRole userOldRole = new SysUserRole();
                userOldRole.setUserId(sy.getUserId());
                userOldRole.setRoleId(oldRoleId);
                userOldRole.setBusinessType(CarTypeEnum.oldCar);
                applyUserRoleService.save(userOldRole);

                // 给临时表绑定角色
                SysUserRoleTemp roleTemp =new SysUserRoleTemp();
                roleTemp.setUserId(sy.getUserId());
                roleTemp.setRoleId(oldRoleId);
                roleTemp.setBusinessType(CarTypeEnum.oldCar);
                applyUserRoleTempService.save(roleTemp);
            }
        }

        // 这边说明是修改权限数据
        SysUserPower power=sysUserPowerService.getOne(Wrappers.<SysUserPower>query().lambda().eq(SysUserPower::getUserId,newUser.getUserId()));
        if(power==null){
            power =new SysUserPower();
            // 说明是新增那么权限表
            power.setUserId(newUser.getUserId());
            power.setChannelId(newUser.getChannelId());
            if(newCarChannelAuthRegion.size() > 0){
                // 说明有新车
                power.setNewApplyPower(StatusEnum.NO.getValue().toString());
                power.setNewAccountPower(StatusEnum.NO.getValue().toString());
            }else {
                power.setNewApplyPower(StatusEnum.NOTHING.getValue().toString());
                power.setNewAccountPower(StatusEnum.NOTHING.getValue().toString());
            }
            if(oldCarChannelAuthRegion.size()>0){
                // 说明有二手车
                power.setOdlApplyPower(StatusEnum.NO.getValue().toString());
                power.setOldAccountPower(StatusEnum.NO.getValue().toString());
            }else {
                power.setOdlApplyPower(StatusEnum.NOTHING.getValue().toString());
                power.setOldAccountPower(StatusEnum.NOTHING.getValue().toString());
            }
            power.setLockFlag(StatusEnum.NO.getValue().toString());
            power.setUserManage(StatusEnum.YES.getValue().toString());
            sysUserPowerService.save(power);

        }else {
            //  说明之前有那么就去修改
            if(newCarChannelAuthRegion.size() > 0){
                // 说明有新车
                if(StatusEnum.NOTHING.getValue().toString().equals(power.getNewApplyPower())||power.getNewApplyPower()==null||power.getNewApplyPower()==""){
                    power.setNewApplyPower(StatusEnum.NO.getValue().toString());
                }
                if(StatusEnum.NOTHING.getValue().toString().equals(power.getNewAccountPower())||power.getNewAccountPower()==null||power.getNewAccountPower()==""){
                    power.setNewAccountPower(StatusEnum.NO.getValue().toString());
                }
            }else {
                power.setNewApplyPower(StatusEnum.NOTHING.getValue().toString());
                power.setNewAccountPower(StatusEnum.NOTHING.getValue().toString());
            }
            if(oldCarChannelAuthRegion.size()>0){
                // 说明有二手车
                if(StatusEnum.NOTHING.getValue().toString().equals(power.getOdlApplyPower())||power.getOdlApplyPower()==null||power.getOdlApplyPower()==""){
                    power.setOdlApplyPower(StatusEnum.NO.getValue().toString());
                }
                if(StatusEnum.NOTHING.getValue().toString().equals(power.getOldAccountPower())||power.getOldAccountPower()==null||power.getOldAccountPower()==""){
                    power.setOldAccountPower(StatusEnum.NO.getValue().toString());
                }
            }else {
                power.setOdlApplyPower(StatusEnum.NOTHING.getValue().toString());
                power.setOldAccountPower(StatusEnum.NOTHING.getValue().toString());
            }
            sysUserPowerService.update(power,Wrappers.<SysUserPower>query().lambda().eq(SysUserPower::getUserId,newUser.getUserId()));
            // 再查询一次权限
            SysUserPower newPower =sysUserPowerService.getOne(Wrappers.<SysUserPower>query().lambda().eq(SysUserPower::getUserId,newUser.getUserId()));
            if(StatusEnum.NOTHING.getValue().toString().equals(newPower.getOldAccountPower().toString())){
                applyUserTempService.update(Wrappers.<SysUserTemp>lambdaUpdate().set(SysUserTemp::getOldStatus,null).eq(SysUserTemp::getId,newUser.getUserId()));
            }else
            if(StatusEnum.NOTHING.getValue().toString().equals(newPower.getNewAccountPower().toString())){
                applyUserTempService.update(Wrappers.<SysUserTemp>lambdaUpdate().set(SysUserTemp::getNewStatus,null).eq(SysUserTemp::getId,newUser.getUserId()));
            }
        }


        // 这边新加的是为了给
        return new IResponse<Boolean>().setMsg("用户创建成功").setData(true);
    }

    @Transactional
    @PostMapping("/syncAuthRegion")
    @ApiOperation(value = "同步渠道授权区域")
    public IResponse<Boolean> syncAuthRegion(@RequestBody ChannelAuthRegionDTO channelAuthRegion) {
        if (ObjectUtils.isEmpty(channelAuthRegion.getRegions())) {
            return new IResponse<Boolean>().setMsg("授权区域regions对象不能为空").setData(false);
        }
        if (ObjectUtils.isEmpty(channelAuthRegion.getType())) {
            return new IResponse<Boolean>().setMsg("同步类型type字段不能为空").setData(false);
        }
        Long channelId = channelAuthRegion.getRegions().get(0).getChannelId();
        SyncTypeEnum type = channelAuthRegion.getType();
//        if (SyncTypeEnum.update == type) {
        //如果是更新，则需要把部门关联的授权区域删除
        // 查询新车的原有数据
        List<SysChannelAuthRegion> newList1 = applyChannelAuthRegionService.list(Wrappers.<SysChannelAuthRegion>query().lambda()
                .eq(SysChannelAuthRegion::getChannelId, channelId).eq(SysChannelAuthRegion::getBusinessType,CarTypeEnum.newCar));
        // 查询二手车原来的数据
        List<SysChannelAuthRegion> oldList1 = applyChannelAuthRegionService.list(Wrappers.<SysChannelAuthRegion>query().lambda()
                .eq(SysChannelAuthRegion::getChannelId, channelId).eq(SysChannelAuthRegion::getBusinessType,CarTypeEnum.oldCar));

        List<SysChannelAuthRegion> list2 = JSONUtil.parseArray(channelAuthRegion.getRegions()).toList(SysChannelAuthRegion.class);

        //获取两个list的不同
        if(newList1.size()>0){
            //  List<String> codes = getDiffrent(list1, list2);
            List<String> codes = getLose(newList1,list2,CarTypeEnum.newCar.toString());
            //根据区域code码和渠道id删除部门授权区域
            if (codes.size()>0) {
                //删除部门的授权区域
                applyDeptAuthRegionService.remove(Wrappers.<SysDeptAuthRegion>query().lambda()
                        .eq(SysDeptAuthRegion::getChannelId, channelId)
                        .in(SysDeptAuthRegion::getCode, codes).eq(SysDeptAuthRegion::getBusinessType,CarTypeEnum.newCar));
            }
        }
        // 去排除二手车的数据
        if(oldList1.size()>0){
            List<String> codes = getLose(oldList1,list2,CarTypeEnum.oldCar.toString());
            //根据区域code码和渠道id删除部门授权区域
            if (codes.size()>0) {
                //删除部门的授权区域
                applyDeptAuthRegionService.remove(Wrappers.<SysDeptAuthRegion>query().lambda()
                        .eq(SysDeptAuthRegion::getChannelId, channelId)
                        .in(SysDeptAuthRegion::getCode, codes).eq(SysDeptAuthRegion::getBusinessType,CarTypeEnum.oldCar));
            }
        }

//        }
        //根据渠道id删除渠道授权区域
        applyChannelAuthRegionService.remove(Wrappers.<SysChannelAuthRegion>query().lambda().eq(SysChannelAuthRegion::getChannelId, channelId));

        //保存新授权区域
        List<SysChannelAuthRegion> list = JSONUtil.parseArray(channelAuthRegion.getRegions()).toList(SysChannelAuthRegion.class);
        int size = list.size();
        if (size <= 1000) {
            applyChannelAuthRegionService.saveBatch(list);
        } else {
            for (int i = 0; i < size / 1000; i++) {
                if (size / 1000 - i > 1) {
                    applyChannelAuthRegionService.saveBatch(list.subList(1000 * i, 1000 * i + 999));
                } else {
                    applyChannelAuthRegionService.saveBatch(list.subList(1000 * i, size - 1));
                }

            }
        }
        List<SysDeptAuthRegion> li =applyDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda()
                .eq(SysDeptAuthRegion::getChannelId, channelId));
        return new IResponse<Boolean>().setMsg("授权区域同步结束").setData(true);
    }

    @Transactional
    @PostMapping("/syncWitnessInfo")
    @ApiOperation(value = "渠道同步见证人信息")
    public IResponse<Boolean> syncWitnessInfo(@RequestBody List<WitnessInfoDTO> witnessInfos) {
        if (ObjectUtils.isEmpty(witnessInfos)) {
            return new IResponse<Boolean>().setMsg("见证人信息不能为空").setData(false);
        }
        List<SysChannelWitnessInfo> list = JSONUtil.parseArray(witnessInfos).toList(SysChannelWitnessInfo.class);
        boolean result = true;
        for (SysChannelWitnessInfo info : list) {
            SysChannelWitnessInfo sysChannelWitnessInfo = applyChannelWitnessInfoService.getOne(Wrappers.<SysChannelWitnessInfo>query().lambda().
                    eq(SysChannelWitnessInfo::getWitnessIdCard, info.getWitnessIdCard()).eq(SysChannelWitnessInfo::getBusinessAttributes, info.getBusinessAttributes()));
            if (sysChannelWitnessInfo != null) {
                SysChannelWitnessInfo ss =new SysChannelWitnessInfo();
                BeanUtils.copyProperties(info, ss);
                ss.setId(sysChannelWitnessInfo.getId());
                result = applyChannelWitnessInfoService.updateById(ss);
            } else {
                result = applyChannelWitnessInfoService.save(info);
            }
        }
        return new IResponse<Boolean>().setMsg("同步见证人成功").setData(result);
    }

    @Transactional
    @PostMapping("/stopWitnessInfo")
    @ApiOperation(value = "停用见证人账号信息")
    public IResponse stopWitnessInfo(@RequestBody List<ChannelCardDTO> cards) {
        if (ObjectUtils.isEmpty(cards)) {
            return new IResponse().fail("见证人证件号码不能为空");
        }
        // 获取需要新车见证人的角色id
        List<Long> newIdCard =applyUserService.getNewIdCarRoleId();


        // 获取需要二手车见证人的数据id
        List<Long> oldIdCard =applyUserService.getOldIdCarRoleId();

        if (cards.size() > 0) {
            for (int i = 0; i < cards.size(); i++) {
                // 去关掉见证人数据信息
                List<SysChannelWitnessInfo> channelWitnessInfos = applyChannelWitnessInfoService.list(Wrappers.<SysChannelWitnessInfo>query().lambda().
                        eq(SysChannelWitnessInfo::getWitnessIdCard, cards.get(i).getCard()).eq(SysChannelWitnessInfo::getChannelId, cards.get(i).getChannelId()));
                if (channelWitnessInfos.size() > 0) {
                    channelWitnessInfos.forEach(en -> {
                        en.setStatus(LockFlagEnum.NO);
                    });
                    applyChannelWitnessInfoService.updateBatchById(channelWitnessInfos);
                }

                // 再关掉权限账号
                List<SysUser> users = applyUserService.list(Wrappers.<SysUser>query().lambda().eq(SysUser::getLockFlag, StatusEnum.NO.getValue())
                        .eq(SysUser::getIdentityNumber, cards.get(i).getCard()));
                if (users.size() > 0) {
                    for (int j = 0; j < users.size(); j++){
                        // 这边需要判断是是不是总账号，如果是总账号就要跳过
                        List<SysUserPower> power = sysUserPowerService.list(Wrappers.<SysUserPower>query().lambda().eq(SysUserPower::getUserId, users.get(j).getUserId()).eq(SysUserPower::getUserManage,StatusEnum.YES.getValue().toString()));
                        if(power.size()>0){
                            // 说明是管理员那么不做处理
                        }else {
                            // 说明是普通账户  这样需要去判断用户是不是需要锁
                            if(CarTypeEnum.newCar.toString().equals(cards.get(i).getBusinessAttributes().toString())){
                                List<SysUserRole> roleList=applyUserRoleService.list(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getUserId,users.get(j).getUserId()).notIn(SysUserRole::getRoleId,newIdCard));
                                if(roleList.size()>0){
                                    // 说明还有其他角色，那么移除其他角色
                                    applyUserRoleService.remove(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getUserId,users.get(j).getUserId()).in(SysUserRole::getRoleId,newIdCard)) ;
                                    // 移除临时角色表数据
                                    applyUserRoleTempService.remove(Wrappers.<SysUserRoleTemp>query().lambda().eq(SysUserRoleTemp::getUserId,users.get(j).getUserId()).in(SysUserRoleTemp::getRoleId,newIdCard));
                                }else {
                                    // 说明没其他角色那么锁上账户
                                    users.get(j).setLockFlag(StatusEnum.YES.getValue());
                                    applyUserService.updateById(users.get(j));
                                    SysUserTemp temp=applyUserTempService.getOne(Wrappers.<SysUserTemp>query().lambda().eq(SysUserTemp::getId,users.get(j).getUserId()));
                                    if(temp!=null){
                                        temp.setLockFlag(StatusEnum.YES.getValue());
                                        applyUserTempService.update(temp,Wrappers.<SysUserTemp>query().lambda().eq(SysUserTemp::getId,users.get(j).getUserId()));
                                        // 去权限做标识
                                        sysUserPowerService.update(Wrappers.<SysUserPower>lambdaUpdate().set(SysUserPower::getStopAccount,StatusEnum.YES.getValue()).eq(SysUserPower::getUserId,users.get(j).getUserId()));
                                    }
                                }
                            }else {
                                // 说明是二手车
                                List<SysUserRole> roleList=applyUserRoleService.list(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getUserId,users.get(j).getUserId()).notIn(SysUserRole::getRoleId,oldIdCard));
                                if(roleList.size()>0){
                                    // 说明还有其他角色，那么移除其他角色
                                    applyUserRoleService.remove(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getUserId,users.get(j).getUserId()).in(SysUserRole::getRoleId,oldIdCard)) ;
                                    // 移除临时角色表数据
                                    applyUserRoleTempService.remove(Wrappers.<SysUserRoleTemp>query().lambda().eq(SysUserRoleTemp::getUserId,users.get(j).getUserId()).in(SysUserRoleTemp::getRoleId,oldIdCard));
                                    // 再去处理进件权限
                                    SysUserPower userPower=sysUserPowerService.getOne(Wrappers.<SysUserPower>query().lambda().eq(SysUserPower::getUserId,users.get(j).getUserId()));
                                    if(userPower!=null){
                                        if(StatusEnum.NO.getValue().toString().equals(userPower.getOdlApplyPower())){
                                            userPower.setOdlApplyPower(StatusEnum.NOTHING.getValue());
                                            sysUserPowerService.update(userPower,Wrappers.<SysUserPower>query().lambda().eq(SysUserPower::getUserId,users.get(j).getUserId()));
                                        }
                                    }
                                }else {
                                    // 说明没其他角色那么锁上账户
                                    users.get(j).setLockFlag(StatusEnum.YES.getValue());
                                    applyUserService.updateById(users.get(j));
                                    // 锁上临时表
                                    SysUserTemp temp=applyUserTempService.getOne(Wrappers.<SysUserTemp>query().lambda().eq(SysUserTemp::getId,users.get(j).getUserId()));
                                    if(temp!=null){
                                        temp.setLockFlag(StatusEnum.YES.getValue());
                                        applyUserTempService.update(temp,Wrappers.<SysUserTemp>query().lambda().eq(SysUserTemp::getId,users.get(j).getUserId()));
                                        // 去权限做标识
                                        sysUserPowerService.update(Wrappers.<SysUserPower>lambdaUpdate().set(SysUserPower::getStopAccount,StatusEnum.YES.getValue()).eq(SysUserPower::getUserId,users.get(j).getUserId()));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return new IResponse().setMsg("停用见证人成功");
    }

    @Transactional
    @PostMapping("/stopWitnessByBlack")
    @ApiOperation(value = "停用见证人,因为加入了黑名单")
    public IResponse stopWitnessByBlack(@RequestBody List<ChannelCardDTO> cards) {
        if (ObjectUtils.isEmpty(cards)) {
            return new IResponse().fail("见证人证件号码不能为空");
        }

        if (cards.size() > 0) {
            for (int i = 0; i < cards.size(); i++) {
                // 去关掉见证人数据信息
                List<SysChannelWitnessInfo> channelWitnessInfos = applyChannelWitnessInfoService.list(Wrappers.<SysChannelWitnessInfo>query().lambda().
                        eq(SysChannelWitnessInfo::getWitnessIdCard, cards.get(i).getCard()).eq(SysChannelWitnessInfo::getChannelId, cards.get(i).getChannelId()));
                if (channelWitnessInfos.size() > 0) {
                    channelWitnessInfos.forEach(en -> {
                        en.setStatus(LockFlagEnum.NO);
                    });
                    applyChannelWitnessInfoService.updateBatchById(channelWitnessInfos);
                }

                // 再关掉权限账号
                List<SysUser> users = applyUserService.list(Wrappers.<SysUser>query().lambda().eq(SysUser::getLockFlag, StatusEnum.NO.getValue())
                        .eq(SysUser::getIdentityNumber, cards.get(i).getCard()));
                if (users.size() > 0) {
                    users.forEach(en -> {
                        en.setLockFlag(StatusEnum.YES.getValue());
                        applyUserService.update(en,Wrappers.<SysUser>query().lambda().eq(SysUser::getUserId,en.getUserId()));
                        applyUserTempService.update(Wrappers.<SysUserTemp>lambdaUpdate().set(SysUserTemp::getLockFlag,StatusEnum.YES.getValue()).eq(SysUserTemp::getId,en.getUserId()));
                        // 去权限做标识
                        sysUserPowerService.update(Wrappers.<SysUserPower>lambdaUpdate().set(SysUserPower::getStopAccount,StatusEnum.YES.getValue()).eq(SysUserPower::getUserId,en.getUserId()));

                    });

                }
            }
        }
        return new IResponse().setMsg("停用见证人成功");
    }

    @Transactional
    @PostMapping("/startWitnessInfo")
    @ApiOperation(value = "启用见证人信息")
    public IResponse startWitnessInfo(@RequestBody List<ChannelCardDTO> cards) {
        if (ObjectUtils.isEmpty(cards)) {
            return new IResponse().fail("见证人证件号码不能为空");
        }

        if (cards.size() > 0) {
            for (int i = 0; i < cards.size(); i++) {
                // 先去启用账号信息
                List<SysChannelWitnessInfo> channelWitnessInfos = applyChannelWitnessInfoService.list(Wrappers.<SysChannelWitnessInfo>query().lambda().
                        eq(SysChannelWitnessInfo::getWitnessIdCard, cards.get(i).getCard()).eq(SysChannelWitnessInfo::getChannelId, cards.get(i).getChannelId()));
                if (channelWitnessInfos.size() > 0) {
                    channelWitnessInfos.forEach(en ->{
                        en.setStatus(LockFlagEnum.YES);
                    });
                    applyChannelWitnessInfoService.updateBatchById(channelWitnessInfos);
                }
                // 再去启用权限账号信息
                List<SysUser> users = applyUserService.list(Wrappers.<SysUser>query().lambda().eq(SysUser::getLockFlag, StatusEnum.YES.getValue())
                        .eq(SysUser::getIdentityNumber, cards.get(i).getCard()).in(SysUser::getChannelId, cards.get(i).getChannelId()));
                if (users.size() > 0) {
                    users.forEach(en -> {
                        en.setLockFlag(StatusEnum.NO.getValue());
                    });
                    applyUserService.updateBatchById(users);
                }
            }
        }
        return new IResponse().setMsg("启用见证人成功");
    }


    @PostMapping("/findWitnessRole")
    @ApiOperation(value = "根据身份证号码查询见证人角色信息")
    public IResponse<List<String>> findWitnessRole(@RequestBody List<ChannelCardDTO> cards) {
        if (ObjectUtils.isEmpty(cards)) {
            return new IResponse().fail("见证人证件号码不能为空");
        }
        List<SysUser> list = new ArrayList<>();
        if (cards.size() > 0) {
            for (int i = 0; i < cards.size(); i++) {
                List<SysUser> users = applyUserService.list(Wrappers.<SysUser>query().lambda().eq(SysUser::getLockFlag, StatusEnum.NO.getValue())
                        .eq(SysUser::getIdentityNumber, cards.get(i).getCard()).eq(SysUser::getChannelId, cards.get(i).getChannelId()));
                list.addAll(users);
            }
        }
        List<String> ids = new ArrayList<>();
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                ids.add(list.get(i).getIdentityNumber());
            }
        }
        return new IResponse<List<String>>().setData(ids);
    }

    @PostMapping("/findDeptByParentId")
    @ApiOperation(value = "根据parentId、channelId获取部门树")
    public IResponse<List<DepartmentDTO>> findDeptByParentId(@RequestParam("parentId") String parentId, @RequestParam("channelId") String channelId) {
        if (ObjectUtils.isEmpty(parentId)) {
            return new IResponse().setMsg("parentId不允许为空").setData(false);
        }
        List<SysDepartment> departments = applyDepartmentService.list(Wrappers.<SysDepartment>query().lambda()
                .eq(SysDepartment::getChannelId, channelId)
                .eq(SysDepartment::getParentId, parentId).orderByAsc(SysDepartment::getSortOrder));
        List<DepartmentDTO> departmentDTOS = JSONUtil.parseArray(departments).toList(DepartmentDTO.class);

        return new IResponse<List<DepartmentDTO>>().setData(departmentDTOS);
    }

    @PostMapping("/findUserByDeptId")
    @ApiOperation(value = "根据部门id获取用户")
    public IResponse<List<UserDTO>> findUserByDeptId(@RequestBody Long deptId) {
        if (ObjectUtils.isEmpty(deptId)) {
            return new IResponse().setMsg("部门id不允许为空").setData(false);
        }
        //获取其下所有部门id
        ArrayList<Long> ids = Lists.newArrayList();
        ids.add(deptId);
        applyDepartmentService.getDepartmentIds(ids, deptId);
        //根据部门id查询用户
        List<SysUser> users = applyUserService.list(Wrappers.<SysUser>query().lambda()
                .in(SysUser::getDeptId, ids));

        List<UserDTO> userDTOS = JSONUtil.parseArray(users).toList(UserDTO.class);
        for (UserDTO dto : userDTOS) {
            dto.setPassword(null);
        }

        return new IResponse<List<UserDTO>>().setData(userDTOS);
    }

    /**
     * 获取两个结果集中不一样的值
     *
     * @param list1
     * @param list2
     * @return
     */
    private static List<String> getDiffrent(List<SysChannelAuthRegion> list1, List<SysChannelAuthRegion> list2) {
        // list1：原来的数据  list2:现在的数据
        List<String> diff = new ArrayList<String>();
        List<SysChannelAuthRegion> maxList = list1;
        List<SysChannelAuthRegion> minList = list2;
        if (list2.size() > list1.size()) {
            maxList = list2;
            minList = list1;
        }
        Map<String, Integer> map = new HashMap<String, Integer>(maxList.size());
        for (SysChannelAuthRegion region : maxList) {
            map.put(region.getCode(), 1);
        }
        for (SysChannelAuthRegion region : minList) {
            if (map.get(region.getCode()) != null) {
                map.put(region.getCode(), 2);
                continue;
            }
            diff.add(region.getCode());
        }

        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            if (entry.getValue() == 1) {
                diff.add(entry.getKey());
            }
        }
        return diff;
    }
    // 获取丢失的省市
    private static List<String> getLose(List<SysChannelAuthRegion> list1, List<SysChannelAuthRegion> list2,String type) {
        List<String> newList = new ArrayList<String>();
        // list1：原来的数据  list2:现在的数据

        // 第一步先把现在所有的数据放在集合里面
        if (list2 != null && !list2.isEmpty()) {
            Map<String, String> dataMap = new HashMap<String, String>();
            for (SysChannelAuthRegion id : list2) {
                if(type.equals(id.getBusinessType().toString())){
                    dataMap.put(id.getCode(), id.getCode());
                }
            }

            //  第二部 把原来的数据现在没有的，就把这个数据存储
            if (list1.size()>0){
                for (SysChannelAuthRegion id : list1) {
                    if (!dataMap.containsKey(id.getCode())) {
                        newList.add(id.getCode());
                    }
                }
            }
            return newList;
        } else {
            return newList;
        }
    }


    @PostMapping("/findDeptInfoByParentId")
    @ApiOperation(value = "根据parentId、channelId获取部门树")
    public IResponse<List<DepartmentDTO>> findDeptInfoByParentId(@RequestParam("parentId") String parentId, @RequestParam("channelId") String channelId) {
        if (ObjectUtils.isEmpty(parentId)) {
            return new IResponse().setMsg("parentId不允许为空").setData(false);
        }
        List<SysDepartment> departments = applyDepartmentService.list(Wrappers.<SysDepartment>query().lambda()
                .eq(SysDepartment::getParentId, parentId)
                .eq(SysDepartment::getChannelId, channelId)
                .orderByAsc(SysDepartment::getSortOrder));
        List<DepartmentDTO> departmentDTOS = JSONUtil.parseArray(setInfo(departments)).toList(DepartmentDTO.class);
        return new IResponse<List<DepartmentDTO>>().setData(departmentDTOS);
    }

    public List<SysDepartment> setInfo(List<SysDepartment> list) {
        list.forEach(item -> {
            if (!CommonConstants.PARENT_ID.equals(Long.valueOf(item.getParentId()))) {
                SysDepartment parent = applyDepartmentService.getById(item.getParentId());
                item.setParentTitle(parent.getTitle());
            } else {
                item.setParentTitle("一级部门");
            }
        });
        return list;
    }

    @Transactional
    @PostMapping("/stopChannel")
    @ApiOperation(value = "渠道同步见证人信息")
    public IResponse<Boolean> stopChannel(@RequestBody List<Long> channelIds) {
        if (ObjectUtils.isEmpty(channelIds)) {
            return new IResponse<Boolean>().setMsg("合作商信息不能为空").setData(false);
        }
        List<SysUser> users = applyUserService.list(Wrappers.<SysUser>query().lambda()
                .in(SysUser::getChannelId, channelIds));
        if (users.size() > 0) {
            users.forEach(en -> {
                en.setLockFlag(StatusEnum.YES.getValue());
            });
            applyUserService.updateBatchById(users);
        }
        return new IResponse<Boolean>().setMsg("停用合作商信息成功！");
    }

    @Transactional
    @PostMapping("/stopUser")
    @ApiOperation(value = "渠道停用账号")
    public IResponse<Boolean> stopUser(@RequestBody StartOrStopDTO dto) {
        if (ObjectUtils.isEmpty(dto.getChannelId())) {
            return new IResponse<Boolean>().setMsg("用户id不能为空").setData(false);
        }
        // 先查询出来管理员的角色id
        List<Long> ids =applyUserService.getAdminId();
        // 新车所有的角色id
        List<Long> newIds =applyUserService.getNewRole();
        // 二手车所有的角色id
        List<Long> oldIds =applyUserService.getOldRole();
        // 看看获取到的用户有没有一个有管理员角色
        List<SysUserPower> userAdminRole =sysUserPowerService.list(Wrappers.<SysUserPower>query().lambda().in(SysUserPower::getUserId,dto.getIds()).eq(SysUserPower::getUserManage,StatusEnum.YES.getValue().toString()));
        List<SysUser> user =applyUserService.list(Wrappers.<SysUser>query().lambda().in(SysUser::getUserId,dto.getIds()));
        if(user.size()<=0){
            throw new AfsBaseException("暂无可以停用的账户！");
        }
        List<SysUser> list =new ArrayList<>();
        if(userAdminRole.size()>0){
            // 说明是管理员，那么我需要停掉所有并且进行记录
            list=applyUserService.list(Wrappers.<SysUser>query().lambda().eq(SysUser::getChannelId,dto.getChannelId()).eq(SysUser::getDelFlag,StatusEnum.NO.getValue()));
        }else {
            list=applyUserService.list(Wrappers.<SysUser>query().lambda().in(SysUser::getUserId,dto.getIds()).eq(SysUser::getDelFlag,StatusEnum.NO.getValue()));

        }
        if(list.size()>0){
            if(CarTypeEnum.newCar.toString().equals(dto.getType())){
                // 进来说明是新车
                for (int i=0;i<list.size();i++){

                    // 先去查询这个用户所有的角色
                    List<SysUserRole> userAllRole =applyUserRoleService.list(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getUserId,list.get(i).getUserId()));
                    // 查询这个用户所有只关于新车的角色（不包含佣金和贷后）
                    List<SysUserRole> userOnlyNewRole =applyUserRoleService.list(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getUserId,list.get(i).getUserId()).in(SysUserRole::getRoleId,newIds));

                    // 这边是判断这个用户属于哪个部门，这个部门是用于新车属性或者二手车属性还是都有。

                    List<SysDeptAuthRegion> newDept=applyDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda().eq(SysDeptAuthRegion::getDeptId,list.get(i).getDeptId()).eq(SysDeptAuthRegion::getChannelId,list.get(i).getChannelId()).eq(SysDeptAuthRegion::getBusinessType,CarTypeEnum.newCar.toString()));

                    List<SysDeptAuthRegion> oldDept=applyDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda().eq(SysDeptAuthRegion::getDeptId,list.get(i).getDeptId()).eq(SysDeptAuthRegion::getChannelId,list.get(i).getChannelId()).eq(SysDeptAuthRegion::getBusinessType,CarTypeEnum.oldCar.toString()));
                    Integer attribute=newDept.size()+oldDept.size();
                    if(attribute==0){
                        throw new AfsBaseException("用户部门数据异常！");
                    }
                    // 去改变停进件表的状态
                    SysUserPower power=sysUserPowerService.getOne(Wrappers.<SysUserPower>query().lambda().eq(SysUserPower::getUserId,list.get(i).getUserId()));
                    if(power!=null){
                        if(StatusEnum.NO.getValue().toString().equals(power.getNewAccountPower())){
                            power.setNewAccountPower(StatusEnum.YES.getValue());
                            // 这边上看看这个部门是不是只有单一的业务类型
                            if(attribute==1){
                                power.setLockFlag(StatusEnum.YES.getValue());
                            }
                            // 如果不是单部门属性那么我就要去看看之前二手车是不是停用状态
                            if(StatusEnum.YES.getValue().toString().equals(power.getOldAccountPower())){
                                power.setLockFlag(StatusEnum.YES.getValue());
                            }
                            if(StatusEnum.NOTHING.getValue().toString().equals(power.getOldAccountPower())){
                                power.setLockFlag(StatusEnum.YES.getValue());
                            }
                            // 这边用于判断虽然我的部门新车二手车都有，但是我只有新车的属性
                            if(userAllRole.size()==userOnlyNewRole.size()){
                                power.setLockFlag(StatusEnum.YES.getValue());
                            }
                            sysUserPowerService.update(power,Wrappers.<SysUserPower>query().lambda().eq(SysUserPower::getUserId,list.get(i).getUserId()));
                            if(StatusEnum.YES.getValue().toString().equals(power.getLockFlag())){
                                // 这边去锁上用户的账号
                                list.get(i).setLockFlag(StatusEnum.YES.getValue());
                                applyUserService.updateById(list.get(i));
                            }

                            if(userOnlyNewRole.size()>0){
                                for (SysUserRole r: userOnlyNewRole) {
                                    // 记录这些批量停用的用户
                                    SysUserStopRecord sr =new SysUserStopRecord();
                                    sr.setUserId(r.getUserId());
                                    sr.setRoleId(r.getRoleId());
                                    sr.setTenantId(r.getTenantId());
                                    sr.setChannelId(dto.getChannelId());
                                    sr.setOperateType(ChannelDic.ACCOUNT);
                                    sr.setBusinessType(dto.getType());
                                    if(userAdminRole.size()>0){
                                        sr.setLotSize(StatusEnum.YES.getValue());
                                    }else {
                                        sr.setLotSize(StatusEnum.NO.getValue());
                                    }
                                    sr.setCreateTime(new Date(System.currentTimeMillis()));
                                    applySysUserStopRecordService.save(sr);
                                }
                                // 移除正式表的这个数据
                                applyUserRoleService.remove(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getUserId,list.get(i).getUserId()).in(SysUserRole::getRoleId,newIds));

                                // 移除临时表的数据
                                applyUserRoleTempService.remove(Wrappers.<SysUserRoleTemp>query().lambda().eq(SysUserRoleTemp::getUserId,list.get(i).getUserId()).in(SysUserRoleTemp::getRoleId,newIds));
                            }else {
                                // 判断是不是管理员   如果不是说明只有佣金和贷后
                                if(StatusEnum.NO.getValue().toString().equals(power.getUserManage())){
                                    // 这边主要是单独记录佣金停的方法（说明这个用户只有佣金或者贷后的角色）
                                    // 记录这些批量停用的用户
                                    SysUserStopRecord sr =new SysUserStopRecord();
                                    sr.setUserId(list.get(i).getUserId());
                                    sr.setRoleId(0L);
                                    sr.setChannelId(dto.getChannelId());
                                    sr.setOperateType(ChannelDic.ACCOUNT);
                                    sr.setBusinessType(dto.getType());
                                    if(userAdminRole.size()>0){
                                        sr.setLotSize(StatusEnum.YES.getValue());
                                    }else {
                                        sr.setLotSize(StatusEnum.NO.getValue());
                                    }
                                    sr.setCreateTime(new Date(System.currentTimeMillis()));
                                    applySysUserStopRecordService.save(sr);
                                }
                            }
                        }
                    }else {
                        throw new AfsBaseException("新车账号权限异常！");
                    }

                }

            }else {
                // 进来说明是二手车
                for (int i=0;i<list.size();i++){
                    // 这边是判断这个用户属于哪个部门，这个部门是用于新车属性或者二手车属性还是都有。

                    List<SysDeptAuthRegion> newDept=applyDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda().eq(SysDeptAuthRegion::getDeptId,list.get(i).getDeptId()).eq(SysDeptAuthRegion::getChannelId,list.get(i).getChannelId()).eq(SysDeptAuthRegion::getBusinessType,CarTypeEnum.newCar.toString()));

                    List<SysDeptAuthRegion> oldDept=applyDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda().eq(SysDeptAuthRegion::getDeptId,list.get(i).getDeptId()).eq(SysDeptAuthRegion::getChannelId,list.get(i).getChannelId()).eq(SysDeptAuthRegion::getBusinessType,CarTypeEnum.oldCar.toString()));
                    Integer attribute=newDept.size()+oldDept.size();
                    if(attribute==0){
                        throw new AfsBaseException("用户部门数据异常！");
                    }
                    // 先去查询这个有没有新车的角色信息
                    List<SysUserRole> userAllRole =applyUserRoleService.list(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getUserId,list.get(i).getUserId()));
                    List<SysUserRole> userOnlyOldRole =applyUserRoleService.list(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getUserId,list.get(i).getUserId()).in(SysUserRole::getRoleId,oldIds));
                    // 去改变停进件表的状态
                    SysUserPower power=sysUserPowerService.getOne(Wrappers.<SysUserPower>query().lambda().eq(SysUserPower::getUserId,list.get(i).getUserId()));
                    if(power!=null){
                        // 这边判断这个角色有没有二手车角色权限
                        if(StatusEnum.NO.getValue().toString().equals(power.getOldAccountPower())){
                            power.setOldAccountPower(StatusEnum.YES.getValue());
                            if(attribute==1){
                                power.setLockFlag(StatusEnum.YES.getValue());
                            }
                            if(StatusEnum.YES.getValue().toString().equals(power.getNewAccountPower())){
                                power.setLockFlag(StatusEnum.YES.getValue());
                            }
                            if(StatusEnum.NOTHING.getValue().toString().equals(power.getNewAccountPower())){
                                power.setLockFlag(StatusEnum.YES.getValue());
                            }
                            if(userAllRole.size()==userOnlyOldRole.size()){
                                power.setLockFlag(StatusEnum.YES.getValue());
                            }
                            sysUserPowerService.update(power,Wrappers.<SysUserPower>query().lambda().eq(SysUserPower::getUserId,list.get(i).getUserId()));
                            if(StatusEnum.YES.getValue().toString().equals(power.getLockFlag())){
                                // 这边去锁上用户的账号
                                list.get(i).setLockFlag(StatusEnum.YES.getValue());
                                applyUserService.updateById(list.get(i));
                            }

                            if(userOnlyOldRole.size()>0){
                                for (SysUserRole r: userOnlyOldRole) {
                                    // 记录这些批量停用的用户
                                    SysUserStopRecord sr =new SysUserStopRecord();
                                    sr.setTenantId(r.getTenantId());
                                    sr.setRoleId(r.getRoleId());
                                    sr.setUserId(r.getUserId());
                                    sr.setChannelId(dto.getChannelId());
                                    sr.setOperateType(ChannelDic.ACCOUNT);
                                    sr.setBusinessType(dto.getType());
                                    if(userAdminRole.size()>0){
                                        sr.setLotSize(StatusEnum.YES.getValue());
                                    }else {
                                        sr.setLotSize(StatusEnum.NO.getValue());
                                    }
                                    sr.setCreateTime(new Date(System.currentTimeMillis()));
                                    applySysUserStopRecordService.save(sr);
                                }
                                applyUserRoleService.remove(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getUserId,list.get(i).getUserId()).in(SysUserRole::getRoleId,oldIds));
                                // 移除二手车的账户数据
                                applyUserRoleTempService.remove(Wrappers.<SysUserRoleTemp>query().lambda().eq(SysUserRoleTemp::getUserId,list.get(i).getUserId()).in(SysUserRoleTemp::getRoleId,oldIds));

                            }else {
                                if(StatusEnum.NO.getValue().toString().equals(power.getUserManage())){
                                    // 这边主要是单独记录佣金停的方法（说明这个用户只有佣金或者贷后的角色）
                                    // 记录这些批量停用的用户
                                    SysUserStopRecord sr =new SysUserStopRecord();
                                    sr.setUserId(list.get(i).getUserId());
                                    sr.setRoleId(0L);
                                    sr.setChannelId(dto.getChannelId());
                                    sr.setOperateType(ChannelDic.ACCOUNT);
                                    sr.setBusinessType(dto.getType());
                                    if(userAdminRole.size()>0){
                                        sr.setLotSize(StatusEnum.YES.getValue());
                                    }else {
                                        sr.setLotSize(StatusEnum.NO.getValue());
                                    }
                                    sr.setCreateTime(new Date(System.currentTimeMillis()));
                                    applySysUserStopRecordService.save(sr);
                                }
                            }
                        }
                    }else {
                        throw new AfsBaseException("新车账号权限异常！");
                    }

                }
            }
            if(userAdminRole.size()>0){
                // 说明有管理员
                // 去单独操作管理员的账户
                List userRoleIds=new ArrayList();
                if(CarTypeEnum.newCar.toString().equals(dto.getType())){
                    // 说明是新车
                    userRoleIds=applyUserService.getNewAdminId();
                }else {
                    //  说明是二手车
                    userRoleIds=applyUserService.getOldAdminId();
                }
                if(userRoleIds.size()>0){
                    List<SysUserRole> adminUserRole =applyUserRoleService.list(Wrappers.<SysUserRole>query().lambda().in(SysUserRole::getUserId,dto.getIds()).in(SysUserRole::getRoleId,userRoleIds));
                    if(adminUserRole.size()>0){
                        applyUserRoleService.remove(Wrappers.<SysUserRole>query().lambda().in(SysUserRole::getUserId,dto.getIds()).in(SysUserRole::getRoleId,userRoleIds));
                        // 移除新临时表的数据
                        applyUserRoleTempService.remove(Wrappers.<SysUserRoleTemp>query().lambda().in(SysUserRoleTemp::getUserId,dto.getIds()).in(SysUserRoleTemp::getRoleId,userRoleIds));

                        // 去记录管理的角色
                        for(int i=0; i<adminUserRole.size();i++){
                            SysUser su=applyUserService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUserId,adminUserRole.get(i).getUserId()));
                            List<SysDeptAuthRegion> newDept=applyDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda().eq(SysDeptAuthRegion::getDeptId,su.getDeptId()).eq(SysDeptAuthRegion::getChannelId,su.getChannelId()).eq(SysDeptAuthRegion::getBusinessType,CarTypeEnum.newCar.toString()));

                            List<SysDeptAuthRegion> oldDept=applyDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda().eq(SysDeptAuthRegion::getDeptId,su.getDeptId()).eq(SysDeptAuthRegion::getChannelId,su.getChannelId()).eq(SysDeptAuthRegion::getBusinessType,CarTypeEnum.oldCar.toString()));
                            Integer attribute=newDept.size()+oldDept.size();
                            if(attribute==0){
                                throw new AfsBaseException("用户部门数据异常！");
                            }

                            //去改变停进件表的状态
                            SysUserPower power=sysUserPowerService.getOne(Wrappers.<SysUserPower>query().lambda().eq(SysUserPower::getUserId,su.getUserId()));
                            if(power!=null){
                                if(CarTypeEnum.newCar.toString().equals(dto.getType())){
                                    // 说明是新车
                                    power.setNewAccountPower(StatusEnum.YES.getValue());
                                    if(attribute==1){
                                        power.setLockFlag(StatusEnum.YES.getValue());
                                    }
                                    if(StatusEnum.YES.getValue().toString().equals(power.getOldAccountPower())){
                                        power.setLockFlag(StatusEnum.YES.getValue());
                                    }
                                    if(StatusEnum.NOTHING.getValue().toString().equals(power.getOldAccountPower())){
                                        power.setLockFlag(StatusEnum.YES.getValue());
                                    }
                                    sysUserPowerService.update(power,Wrappers.<SysUserPower>query().lambda().eq(SysUserPower::getUserId,su.getUserId()));
                                    if(StatusEnum.YES.getValue().toString().equals(power.getLockFlag())){
                                        su.setLockFlag(StatusEnum.YES.getValue());
                                        applyUserService.updateById(su);
                                    }
                                }else {
                                    // 说明是二手车
                                    power.setOldAccountPower(StatusEnum.YES.getValue());
                                    if(attribute==1){
                                        power.setLockFlag(StatusEnum.YES.getValue());
                                    }
                                    if(StatusEnum.YES.getValue().toString().equals(power.getNewAccountPower())){
                                        power.setLockFlag(StatusEnum.YES.getValue());
                                    }
                                    if(StatusEnum.NOTHING.getValue().toString().equals(power.getNewAccountPower())){
                                        power.setLockFlag(StatusEnum.YES.getValue());
                                    }
                                    sysUserPowerService.update(power,Wrappers.<SysUserPower>query().lambda().eq(SysUserPower::getUserId,su.getUserId()));
                                    if(StatusEnum.YES.getValue().toString().equals(power.getLockFlag())){
                                        su.setLockFlag(StatusEnum.YES.getValue());
                                        applyUserService.updateById(su);
                                    }
                                }
                            }else {
                                throw new AfsBaseException("管理员权限数据异常！");
                            }

                            // 记录这些批量停用的用户
                            SysUserStopRecord sr =new SysUserStopRecord();
                            sr.setUserId(adminUserRole.get(i).getUserId());
                            sr.setRoleId(adminUserRole.get(i).getRoleId());
                            sr.setTenantId(adminUserRole.get(i).getTenantId());
                            sr.setChannelId(dto.getChannelId());
                            sr.setOperateType(ChannelDic.ACCOUNT);
                            sr.setBusinessType(dto.getType());
                            sr.setLotSize(StatusEnum.YES.getValue());
                            sr.setCreateTime(new Date(System.currentTimeMillis()));
                            applySysUserStopRecordService.save(sr);
                        }
                    }
                }
            }
        }else {
            throw  new AfsBaseException("操作账号权限数据异常!");
        }

        return new IResponse<Boolean>().setMsg("停用成功！");
    }


    @Transactional
    @PostMapping("/startUser")
    @ApiOperation(value = "渠道启用账号")
    public IResponse<Boolean> startUser(@RequestBody StartOrStopDTO dto) {
        if (ObjectUtils.isEmpty(dto)) {
            return new IResponse<Boolean>().setMsg("用户id不能为空").setData(false);
        }
        // 先查询出来管理员的角色id
        List<Long> ids =applyUserService.getAdminId();
        // 看看获取到的用户有没有一个有管理员角色
        List<SysUserPower> userAdminRole =sysUserPowerService.list(Wrappers.<SysUserPower>query().lambda().in(SysUserPower::getUserId,dto.getIds()).eq(SysUserPower::getUserManage,StatusEnum.YES.getValue().toString()));
        List<SysUser> user =applyUserService.list(Wrappers.<SysUser>query().lambda().in(SysUser::getUserId,dto.getIds()));
        if(user.size()<=0){
            throw new AfsBaseException("暂无可以启用的用户！");
        }
        List<SysUserStopRecord> sr =new ArrayList<>();
        List<Long> startUserIds =new ArrayList<>();

        if(userAdminRole.size()>0){
            // 说明是管理员 我要把批量停用的给还原回去
            sr=applySysUserStopRecordService.list(Wrappers.<SysUserStopRecord>query().lambda().eq(SysUserStopRecord::getChannelId,dto.getChannelId()).eq(SysUserStopRecord::getBusinessType,dto.getType()).eq(SysUserStopRecord::getOperateType,ChannelDic.ACCOUNT).eq(SysUserStopRecord::getLotSize,StatusEnum.YES.getValue().toString()));
        }else {
            // 获取数据看看这个用户是不是管理员
            sr=applySysUserStopRecordService.list(Wrappers.<SysUserStopRecord>query().lambda().in(SysUserStopRecord::getUserId,dto.getIds()).eq(SysUserStopRecord::getBusinessType,dto.getType()).eq(SysUserStopRecord::getOperateType,ChannelDic.ACCOUNT));
        }
        if(sr.size()>0){
            for (int i=0;i<sr.size();i++){
                // RoleId 是0 的时候是为了标记 是佣金和贷后，但是佣金和贷后又没有把角色（也有可能是管理员）
                if(!sr.get(i).getRoleId().toString().equals("0")){
                    // 先去查查这个角色他现在还有没有，如果没有就给，有就不给了
                    SysUserRole sur=applyUserRoleService.getOne(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getRoleId,sr.get(i).getRoleId()).eq(SysUserRole::getUserId,sr.get(i).getUserId()).eq(SysUserRole::getBusinessType,sr.get(i).getBusinessType()));
                    if(sur==null){
                        SysUserRole Role =new  SysUserRole();
                        Role.setUserId(sr.get(i).getUserId());
                        Role.setRoleId(sr.get(i).getRoleId());
                        if(CarTypeEnum.newCar.toString().equals(dto.getType())){
                            Role.setBusinessType(CarTypeEnum.newCar);
                        }else {
                            Role.setBusinessType(CarTypeEnum.oldCar);
                        }
                        applyUserRoleService.save(Role);
                    }
                    // 去查询临时表的这表数据
                    SysUserRoleTemp surTemp=applyUserRoleTempService.getOne(Wrappers.<SysUserRoleTemp>query().lambda().eq(SysUserRoleTemp::getRoleId,sr.get(i).getRoleId()).eq(SysUserRoleTemp::getUserId,sr.get(i).getUserId()).eq(SysUserRoleTemp::getBusinessType,sr.get(i).getBusinessType()));
                    if(surTemp==null){
                        SysUserRoleTemp roleTemp =new  SysUserRoleTemp();
                        roleTemp.setUserId(sr.get(i).getUserId());
                        roleTemp.setRoleId(sr.get(i).getRoleId());
                        if(CarTypeEnum.newCar.toString().equals(dto.getType())){
                            roleTemp.setBusinessType(CarTypeEnum.newCar);
                        }else {
                            roleTemp.setBusinessType(CarTypeEnum.oldCar);
                        }
                        applyUserRoleTempService.save(roleTemp);
                    }
                }
                startUserIds.add(sr.get(i).getUserId());
            }

        }

        // 查询这些用户的权限
        List<SysUserPower> powerList=sysUserPowerService.list(Wrappers.<SysUserPower>query().lambda().in(SysUserPower::getUserId,startUserIds));
        if(powerList.size()>0) {
            for (SysUserPower userPower : powerList) {
                if (CarTypeEnum.newCar.toString().equals(dto.getType())) {
                    // 说明是新车
                    userPower.setNewAccountPower(StatusEnum.NO.getValue());
                    if (StatusEnum.YES.getValue().equals(userPower.getLockFlag())) {
                        // 这边说明因为停账号所以才被锁上的
                        userPower.setLockFlag(StatusEnum.NO.getValue());
                        // 去解除用户的账号状态
                        SysUser sysUser = applyUserService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUserId, userPower.getUserId()));
                        sysUser.setLockFlag(StatusEnum.NO.getValue());
                        applyUserService.update(sysUser, Wrappers.<SysUser>query().lambda().eq(SysUser::getUserId, sysUser.getUserId()));
                    }
                    sysUserPowerService.update(userPower, Wrappers.<SysUserPower>query().lambda().eq(SysUserPower::getUserId, userPower.getUserId()));
                } else {
                    userPower.setOldAccountPower(StatusEnum.NO.getValue());
                    if (CarTypeEnum.oldCar.toString().equals(dto.getType())) {
                        // 说明是新车
                        userPower.setOldAccountPower(StatusEnum.NO.getValue());
                        if (StatusEnum.YES.getValue().equals(userPower.getLockFlag())) {
                            // 这边说明因为停账号所以才被锁上的
                            userPower.setLockFlag(StatusEnum.NO.getValue());
                            // 去解除用户的账号状态
                            SysUser sysUser = applyUserService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUserId, userPower.getUserId()));
                            sysUser.setLockFlag(StatusEnum.NO.getValue());
                            applyUserService.update(sysUser, Wrappers.<SysUser>query().lambda().eq(SysUser::getUserId, sysUser.getUserId()));
                        }
                        sysUserPowerService.update(userPower, Wrappers.<SysUserPower>query().lambda().eq(SysUserPower::getUserId, userPower.getUserId()));
                    }
                }
            }

            // 这边要去判断新车或者二手车的账号数量是否超限制
            // 先查询 这个账户新车可以创建多少
//            SysChannelBasicInfo one = applyChannelBasicInfoService.getOne(Wrappers.<SysChannelBasicInfo>lambdaQuery().eq(SysChannelBasicInfo::getChannelId, dto.getChannelId()));
//            if (one != null) {
//                Integer newCount = one.getNewCarUserHierarchy();
//                Integer oldCount = one.getOldCarUserHierarchy();
//                Integer userNewCount = applyUserMapper.findUserCount(CarTypeEnum.newCar.toString(), dto.getChannelId());
//                Integer userOldCount = applyUserMapper.findUserCount(CarTypeEnum.oldCar.toString(), dto.getChannelId());
//                if (CarTypeEnum.newCar.toString().equals(dto.getType())) {
//                    if (userNewCount > newCount) {
//                        throw new AfsBaseException("启用的新车账号数量超出最大限制！");
//                    }
//                } else {
//                    if (userOldCount > oldCount) {
//                        throw new AfsBaseException("启用的二手车车账号数量超出最大限制！");
//                    }
//                }
//            } else {
//                throw new AfsBaseException("获取渠道用户信息失败！");
//            }
            // 新版的校验
            this.checkUserCount(dto.getChannelId(),dto.getType());
            // 去删除表中的数据
            if (userAdminRole.size() > 0) {
                // 说明是管理员
                applySysUserStopRecordService.remove(Wrappers.<SysUserStopRecord>query().lambda().eq(SysUserStopRecord::getChannelId, dto.getChannelId()).eq(SysUserStopRecord::getBusinessType, dto.getType()).eq(SysUserStopRecord::getOperateType, ChannelDic.ACCOUNT).eq(SysUserStopRecord::getLotSize,StatusEnum.YES.getValue().toString()));
            } else {
                // 说明不是管理员
                applySysUserStopRecordService.remove(Wrappers.<SysUserStopRecord>query().lambda().in(SysUserStopRecord::getUserId, dto.getIds()).eq(SysUserStopRecord::getBusinessType, dto.getType()).eq(SysUserStopRecord::getOperateType, ChannelDic.ACCOUNT));
            }
        }
        return new IResponse<Boolean>().setMsg("启用成功！");
    }


    @Transactional
    @PostMapping("/stopApply")
    @ApiOperation(value = "渠道停用进件")
    public IResponse<Boolean> stopApply(@RequestBody StartOrStopDTO dto) {
        if (ObjectUtils.isEmpty(dto)) {
            return new IResponse<Boolean>().setMsg("用户id不能为空").setData(false);
        }
        // 先查询出来管理员的角色id
        List<Long> ids =applyUserService.getAdminId();
        // 查询新车 所有的进件角色
        List<Long> newIds =applyUserService.getNewApply();
        // 查询 二手车所有的进件角色
        List<Long> oldIds =applyUserService.getOldApply();

        SysRole seeRole =applyRoleService.getOne(Wrappers.<SysRole>query().lambda().eq(SysRole::getRoleCode,AfsEnumUtil.key(RoleEnum.ROLE_APPLY_QUERY.name())));
        // 看看获取到的用户有没有一个有管理员角色
        List<SysUserPower> userAdminRole =sysUserPowerService.list(Wrappers.<SysUserPower>query().lambda().in(SysUserPower::getUserId,dto.getIds()).eq(SysUserPower::getUserManage,StatusEnum.YES.getValue().toString()));
        List<SysUser> list =new ArrayList<>();
        // 判断是不是管理员
        if(userAdminRole.size()>0){
            // 说明是管理员，那么就要停掉所有的进件
            list=applyUserService.list(Wrappers.<SysUser>query().lambda().eq(SysUser::getChannelId,dto.getChannelId()).eq(SysUser::getDelFlag,StatusEnum.NO.getValue()));
        }else {
            list=applyUserService.list(Wrappers.<SysUser>query().lambda().in(SysUser::getUserId,dto.getIds()).eq(SysUser::getDelFlag,StatusEnum.NO.getValue()));
        }
        if(list.size()>0){
            // 去改变停进件表的状态
            if(CarTypeEnum.newCar.toString().equals(dto.getType())){
                for (int i=0;i<list.size();i++){
                    // 去改  用户进件权限表
                    SysUserPower power=sysUserPowerService.getOne(Wrappers.<SysUserPower>query().lambda().eq(SysUserPower::getUserId,list.get(i).getUserId()));
                    if(power!=null){
                        if(StatusEnum.NO.getValue().toString().equals(power.getNewApplyPower())){
                            //  说明用户属于新车进件启用状态
                            power.setNewApplyPower(StatusEnum.YES.getValue());
                            sysUserPowerService.update(power,Wrappers.<SysUserPower>query().lambda().eq(SysUserPower::getUserId,list.get(i).getUserId()));
                            //  去存储这个用户被停的进件角色
                            List<SysUserRole> userApplyRole =applyUserRoleService.list(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getUserId,list.get(i).getUserId()).in(SysUserRole::getRoleId,newIds).eq(SysUserRole::getBusinessType,dto.getType()));
                            if(userApplyRole.size()>0){
                                for (int j=0;j<userApplyRole.size();j++){
                                    // 记录这些批量停用的进件用户
                                    SysUserStopRecord sr =new SysUserStopRecord();
                                    sr.setUserId(userApplyRole.get(j).getUserId());
                                    sr.setRoleId(userApplyRole.get(j).getRoleId());
                                    sr.setChannelId(dto.getChannelId());
                                    sr.setOperateType(ChannelDic.APPLY);
                                    sr.setCreateTime(new Date(System.currentTimeMillis()));
                                    sr.setBusinessType(dto.getType());
                                    if(userAdminRole.size()>0){
                                        sr.setLotSize(StatusEnum.YES.getValue());
                                    }else {
                                        sr.setLotSize(StatusEnum.NO.getValue());
                                    }
                                    applySysUserStopRecordService.save(sr);
                                }
                                // 再去删掉这些数据
                                applyUserRoleService.remove(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getUserId,list.get(i).getUserId()).in(SysUserRole::getRoleId,newIds).eq(SysUserRole::getBusinessType,dto.getType()));
                                // 移除临时表的数据
                                applyUserRoleTempService.remove(Wrappers.<SysUserRoleTemp>query().lambda().eq(SysUserRoleTemp::getUserId,list.get(i).getUserId()).in(SysUserRoleTemp::getRoleId,newIds).eq(SysUserRoleTemp::getBusinessType,dto.getType()));

                                // 再给他赋值一个  置换的角色
                                // 先去查查他有没有被置换的角色  如果没有就赋值一个给他
                                List<SysUserRole> userRoleList =applyUserRoleService.list(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getRoleId,seeRole.getId()).eq(SysUserRole::getUserId,list.get(i).getUserId()).eq(SysUserRole::getBusinessType,CarTypeEnum.newCar.toString()));
                                if(userRoleList.size()>0){
                                    // 说明已存在置换的新车查看权限
                                }else {
                                    // 新增一个新车的查看权限
                                    SysUserRole userNewRole = new SysUserRole();
                                    userNewRole.setUserId(list.get(i).getUserId());
                                    userNewRole.setRoleId(seeRole.getId());
                                    userNewRole.setBusinessType(CarTypeEnum.newCar);
                                    applyUserRoleService.save(userNewRole);
                                }

                            }
                        }
                    }else {
                        throw new AfsBaseException("用户停新车进件数据有误！");
                    }

                }
            }else {
                for (int i=0;i<list.size();i++){
                    // 去改  用户进件权限表
                    SysUserPower power=sysUserPowerService.getOne(Wrappers.<SysUserPower>query().lambda().eq(SysUserPower::getUserId,list.get(i).getUserId()));
                    if(power!=null){
                        if(StatusEnum.NO.getValue().toString().equals(power.getOdlApplyPower())){
                            power.setOdlApplyPower(StatusEnum.YES.getValue());
                            sysUserPowerService.update(power,Wrappers.<SysUserPower>query().lambda().eq(SysUserPower::getUserId,list.get(i).getUserId()));

                            List<SysUserRole> role =applyUserRoleService.list(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getUserId,list.get(i).getUserId()).in(SysUserRole::getRoleId,oldIds).eq(SysUserRole::getBusinessType,dto.getType()));
                            if(role.size()>0){
                                for (int j=0;j<role.size();j++){
                                    // 记录这些批量停用的进件用户
                                    SysUserStopRecord sr =new SysUserStopRecord();
                                    sr.setUserId(role.get(j).getUserId());
                                    sr.setRoleId(role.get(j).getRoleId());
                                    sr.setChannelId(dto.getChannelId());
                                    sr.setOperateType(ChannelDic.APPLY);
                                    sr.setCreateTime(new Date(System.currentTimeMillis()));
                                    sr.setBusinessType(dto.getType());
                                    if(userAdminRole.size()>0){
                                        sr.setLotSize(StatusEnum.YES.getValue());
                                    }else {
                                        sr.setLotSize(StatusEnum.NO.getValue());
                                    }
                                    applySysUserStopRecordService.save(sr);
                                }
                                // 再去删掉这些数据
                                applyUserRoleService.remove(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getUserId,list.get(i).getUserId()).in(SysUserRole::getRoleId,oldIds).eq(SysUserRole::getBusinessType,dto.getType()));
                                // 移除临时表的状态
                                applyUserRoleTempService.remove(Wrappers.<SysUserRoleTemp>query().lambda().eq(SysUserRoleTemp::getUserId,list.get(i).getUserId()).in(SysUserRoleTemp::getRoleId,oldIds).eq(SysUserRoleTemp::getBusinessType,dto.getType()));

                                // 再给他赋值一个  置换的角色
                                // 先去查查他有没有被置换的角色  如果没有就赋值一个给他
                                List<SysUserRole> userRoleList =applyUserRoleService.list(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getRoleId,seeRole.getId()).eq(SysUserRole::getUserId,list.get(i).getUserId()).eq(SysUserRole::getBusinessType,CarTypeEnum.oldCar.toString()));
                                if(userAdminRole.size()>0){
                                    // 说明我有二手车进件查看权限
                                }else {
                                    SysUserRole userNewRole = new SysUserRole();
                                    userNewRole.setUserId(list.get(i).getUserId());
                                    userNewRole.setRoleId(seeRole.getId());
                                    userNewRole.setBusinessType(CarTypeEnum.oldCar);
                                    applyUserRoleService.save(userNewRole);
                                }

                            }
                        }

                    }else {
                        throw  new AfsBaseException("用户停二手车进件数据错误！");
                    }

                }
            }
        }

        return new IResponse<Boolean>().setMsg("停用成功！");
    }

    @Transactional
    @PostMapping("/startApply")
    @ApiOperation(value = "渠道启用进件")
    public IResponse<Boolean> startApply(@RequestBody StartOrStopDTO dto) {
        if (ObjectUtils.isEmpty(dto)) {
            return new IResponse<Boolean>().setMsg("用户id不能为空").setData(false);
        }
        // 先查询出来管理员的角色id
        List<Long> ids =applyUserService.getAdminId();
        SysRole uRole =applyRoleService.getOne(Wrappers.<SysRole>query().lambda().eq(SysRole::getRoleCode,AfsEnumUtil.key(RoleEnum.ROLE_APPLY_QUERY.name())));
        // 看看获取到的用户有没有一个有管理员角色
        List<SysUserPower> userAdminRole =sysUserPowerService.list(Wrappers.<SysUserPower>query().lambda().in(SysUserPower::getUserId,dto.getIds()).eq(SysUserPower::getUserManage,StatusEnum.YES.getValue().toString()));
        List<SysUserStopRecord> sr =new ArrayList<>();

        List<Long> userPowerIds =new ArrayList<>();
        if(userAdminRole.size()>0){
            // 说明是管理员  我需要把所有的用户数据还回去
            sr=applySysUserStopRecordService.list(Wrappers.<SysUserStopRecord>query().lambda().eq(SysUserStopRecord::getChannelId,dto.getChannelId()).eq(SysUserStopRecord::getBusinessType,dto.getType()).eq(SysUserStopRecord::getOperateType,ChannelDic.APPLY).eq(SysUserStopRecord::getLotSize,StatusEnum.YES.getValue().toString()));
        }else {
            // 获取数据看看这个用户是不是管理员
            sr=applySysUserStopRecordService.list(Wrappers.<SysUserStopRecord>query().lambda().in(SysUserStopRecord::getUserId,dto.getIds()).eq(SysUserStopRecord::getBusinessType,dto.getType()).eq(SysUserStopRecord::getOperateType,ChannelDic.APPLY));
        }
        if(sr.size()>0){
            for (int i=0;i<sr.size();i++){

                // 先去查查这个角色他现在还有没有，如果没有就给，有就不给了
                SysUserRole sur=applyUserRoleService.getOne(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getRoleId,sr.get(i).getRoleId()).eq(SysUserRole::getUserId,sr.get(i).getUserId()).eq(SysUserRole::getBusinessType,sr.get(i).getBusinessType()));
                if(sur==null){
                    SysUserRole Role =new  SysUserRole();
                    Role.setUserId(sr.get(i).getUserId());
                    Role.setRoleId(sr.get(i).getRoleId());
                    if(CarTypeEnum.newCar.toString().equals(dto.getType())){
                        Role.setBusinessType(CarTypeEnum.newCar);
                    }else {
                        Role.setBusinessType(CarTypeEnum.oldCar);
                    }
                    applyUserRoleService.save(Role);
                }

                // 去改变临时表的数据
                SysUserRoleTemp surTemp=applyUserRoleTempService.getOne(Wrappers.<SysUserRoleTemp>query().lambda().eq(SysUserRoleTemp::getRoleId,sr.get(i).getRoleId()).eq(SysUserRoleTemp::getUserId,sr.get(i).getUserId()).eq(SysUserRoleTemp::getBusinessType,sr.get(i).getBusinessType()));
                if(surTemp==null){
                    SysUserRoleTemp role =new  SysUserRoleTemp();
                    role.setUserId(sr.get(i).getUserId());
                    role.setRoleId(sr.get(i).getRoleId());
                    if(CarTypeEnum.newCar.toString().equals(dto.getType())){
                        role.setBusinessType(CarTypeEnum.newCar);
                    }else {
                        role.setBusinessType(CarTypeEnum.oldCar);
                    }
                    applyUserRoleTempService.save(role);
                }
                userPowerIds.add(sr.get(i).getUserId());
                // 如果是新车清除新车置换的角色
                applyUserRoleService.remove(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getRoleId,uRole.getId()).eq(SysUserRole::getUserId,sr.get(i).getUserId()).eq(SysUserRole::getBusinessType,sr.get(i).getBusinessType()));
            }
        }
        // 去删除表中的数据
        if(userAdminRole.size()>0){
            // 说明是管理员
            applySysUserStopRecordService.remove(Wrappers.<SysUserStopRecord>query().lambda().eq(SysUserStopRecord::getChannelId,dto.getChannelId()).eq(SysUserStopRecord::getBusinessType,dto.getType()).eq(SysUserStopRecord::getOperateType,ChannelDic.APPLY).eq(SysUserStopRecord::getLotSize,StatusEnum.YES.getValue()));

        }else {
            // 说明不是管理员
            applySysUserStopRecordService.remove(Wrappers.<SysUserStopRecord>query().lambda().in(SysUserStopRecord::getUserId,dto.getIds()).eq(SysUserStopRecord::getBusinessType,dto.getType()).eq(SysUserStopRecord::getOperateType,ChannelDic.APPLY));

        }
        // 改变权限表的进件状态
        if(userPowerIds.size()>0){
            List<SysUserPower> userPowerList =sysUserPowerService.list(Wrappers.<SysUserPower>query().lambda().in(SysUserPower::getUserId,userPowerIds));
            if(userPowerList.size()>0){
                for (SysUserPower userPower:userPowerList){
                    if(CarTypeEnum.newCar.toString().equals(dto.getType())){
                        // 说明是新车
                        if(StatusEnum.NOTHING.getValue().toString().equals(userPower.getNewApplyPower())){
                            throw new AfsBaseException("用户启用新车进件数据有误！");
                        }else {
                            userPower.setNewApplyPower(StatusEnum.NO.getValue());
                        }
                        sysUserPowerService.update(userPower,Wrappers.<SysUserPower>query().lambda().eq(SysUserPower::getUserId,userPower.getUserId()));
                    }else {
                        // 说明是二手车
                        if(StatusEnum.NOTHING.getValue().toString().equals(userPower.getOdlApplyPower())){
                            throw new AfsBaseException("用户启用二手车进件数据有误！");
                        }else {
                            userPower.setOdlApplyPower(StatusEnum.NO.getValue());
                        }
                        sysUserPowerService.update(userPower,Wrappers.<SysUserPower>query().lambda().eq(SysUserPower::getUserId,userPower.getUserId()));
                    }
                }
            }
        }


        //  如果是管理员那么去更新管理员的状态
        if(userAdminRole.size()>0){
            SysUserPower adminPower =sysUserPowerService.getOne(Wrappers.<SysUserPower>query().lambda().eq(SysUserPower::getChannelId,dto.getChannelId()).eq(SysUserPower::getUserManage,StatusEnum.YES.getValue()));
            if(adminPower!=null){
                if(CarTypeEnum.newCar.toString().equals(dto.getType())){
                    if(StatusEnum.NOTHING.getValue().toString().equals(adminPower.getNewApplyPower())){
                        throw new AfsBaseException("管理员新车进件数据异常！");
                    }else {
                        adminPower.setNewApplyPower(StatusEnum.NO.getValue());
                        sysUserPowerService.update(adminPower,Wrappers.<SysUserPower>query().lambda().eq(SysUserPower::getUserId,adminPower.getUserId()));
                    }
                }else {
                    if(StatusEnum.NOTHING.getValue().toString().equals(adminPower.getOdlApplyPower())){
                        throw new AfsBaseException("管理员二手车进件数据异常！");
                    }else {
                        adminPower.setOdlApplyPower(StatusEnum.NO.getValue());
                        sysUserPowerService.update(adminPower,Wrappers.<SysUserPower>query().lambda().eq(SysUserPower::getUserId,adminPower.getUserId()));
                    }
                }
            }else {
                throw new AfsBaseException("管理员进件数据异常！");
            }
        }

        return new IResponse<Boolean>().setMsg("启用成功！");
    }

    @Transactional
    @PostMapping("/checkWitness")
    @ApiOperation(value = "校验见证人是否被其他公司使用")
    public IResponse <Boolean> checkWitness(@RequestBody List<ChannelCardDTO> cards) {
        if (ObjectUtils.isEmpty(cards)) {
            return new IResponse().fail("见证人证件号码不能为空");
        }
        for(ChannelCardDTO dto :cards){
            // 查询这个用户有没有在其他合作商有启用的账号
            List<SysUser> list= applyUserService.list(Wrappers.<SysUser>query().lambda()
                    .eq(SysUser::getIdentityNumber, dto.getCard())
                    .notIn(SysUser::getChannelId, dto.getChannelId()).eq(SysUser::getLockFlag,StatusEnum.NO.getValue().toString()));
            if(list.size()>0){
                return new IResponse<Boolean>().setData(true).setMsg("重复备案！");
            }
        }
        return new IResponse<Boolean>().setData(false).setMsg("校验成功！");
    }

    // 写这个方法去校验用户数量是否超限制
    public  void  checkUserCount(Long channelId,String type){
        // 声明一个新车的部门集合
        List<Long> newDepart=new ArrayList<>();
        // 声明一个二手车部门的集合
        List<Long> oldDepart=new ArrayList<>();


        // 先查出来这个合作商所有的部门
        List<SysDepartment> list=applyDepartmentService.list(Wrappers.<SysDepartment>query().lambda().eq(SysDepartment::getChannelId,channelId));
        if(list.size()>0){
            for(SysDepartment department:list){
                // 根据部门id 查询这个部门属于新车部门还是二手车部门
                //部门新车权限
                List<SysDeptAuthRegion> newDept=applyDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda().eq(SysDeptAuthRegion::getDeptId,department.getId()).eq(SysDeptAuthRegion::getBusinessType,CarTypeEnum.newCar.toString()));
                // 部门二手车权限
                List<SysDeptAuthRegion> oldDept=applyDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda().eq(SysDeptAuthRegion::getDeptId,department.getId()).eq(SysDeptAuthRegion::getBusinessType,CarTypeEnum.oldCar.toString()));
                if(newDept.size()>0&&oldDept.size()>0){
                    newDepart.add(department.getId());
                    oldDepart.add(department.getId());
                }else if(newDept.size()>0){
                    newDepart.add(department.getId());
                }else if(oldDepart.size()>0){
                    oldDepart.add(department.getId());
                }
            }

            // 这边开始计算数量
            SysChannelBasicInfo one = applyChannelBasicInfoService.getOne(Wrappers.<SysChannelBasicInfo>lambdaQuery().eq(SysChannelBasicInfo::getChannelId, channelId));
            if (one != null) {
                Integer newCount = one.getNewCarUserHierarchy();
                Integer oldCount = one.getOldCarUserHierarchy();
                Integer userNewCount=0;
                Integer userOldCount=0;
                if(newDepart.size()>0){
                    userNewCount = applyUserMapper.findUserCountByDepart(CarTypeEnum.newCar.toString(), channelId,newDepart);
                }
                if(oldDepart.size()>0){
                    userOldCount = applyUserMapper.findUserCountByDepart(CarTypeEnum.oldCar.toString(), channelId,oldDepart);
                }
                if(CarTypeEnum.newCar.toString().equals(type)){
                    if (newCount!=null) {
                        if (userNewCount > newCount) {
                            throw new AfsBaseException("启用的新车账号数量超出最大限制！");
                        }
                    }
                }else if(CarTypeEnum.oldCar.toString().equals(type)) {
                    if(oldCount!=null){
                        if (userOldCount > oldCount) {
                            throw new AfsBaseException("启用的二手车车账号数量超出最大限制！");
                        }
                    }
                }else {
                    if (newCount!=null) {
                        if (userNewCount > newCount) {
                            throw new AfsBaseException("启用的新车账号数量超出最大限制！");
                        }
                    }
                    if(oldCount!=null){
                        if (userOldCount > oldCount) {
                            throw new AfsBaseException("启用的二手车车账号数量超出最大限制！");
                        }
                    }
                }


            } else {
                throw new AfsBaseException("获取渠道用户信息失败！");
            }
        }else {

        }
    }
}
